const Router = require('koa-router')
const { resDesign } = require('@/utils/dataDesign')
const SystemService = require('@/service/system.service')
const HTTP_CODE = require('@/app/http-code')

const dictRouter = new Router({ prefix: '/system/dict' })

// 类型列表
dictRouter.get('/type', async (ctx) => {
  try {
    const data = await SystemService.selectDictType(ctx.query)
    ctx.body = resDesign({ data })
  } catch (error) {
    console.log(error)
  }
})
// 新增字典类型
dictRouter.post('/type/insert', async (ctx) => {
  try {
    await SystemService.insertDictType(ctx.request.body)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error.sqlMessage)
    ctx.body = resDesign({ code: HTTP_CODE.error, msg: error.sqlMessage })
  }
})
// 编辑字典类型
dictRouter.patch('/type/update', async (ctx) => {
  try {
    await SystemService.updateDictType(ctx.request.body)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error)
  }
})
// 删除字典类型
dictRouter.delete('/type/delect/:id', async (ctx) => {
  try {
    const { id } = ctx.params
    await SystemService.delectDictType(id)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error)
  }
})

// 根据字典类型查询数据
dictRouter.get('/data/:dictType', async (ctx) => {
  try {
    const data = await SystemService.selectDictData(ctx.params)
    ctx.body = resDesign({ data })
  } catch (error) {
    console.log(error)
  }
})
// 新建字典数据
dictRouter.post('/data/insert', async (ctx) => {
  try {
    await SystemService.insertDictData(ctx.request.body)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error)
    ctx.body = resDesign({ code: HTTP_CODE.error, msg: error.sqlMessage })
  }
})
// 编辑字典数据
dictRouter.patch('/data/update', async (ctx) => {
  try {
    await SystemService.updateDictData(ctx.request.body)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error)
  }
})
// 删除字典数据
dictRouter.delete('/data/delete/:id', async (ctx) => {
  try {
    const { id } = ctx.params
    await SystemService.deleteDictData(id)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error)
  }
})

// vue组件接口：根据字典类型查询状态为正常的字典数据
dictRouter.get('/:dictType', async (ctx) => {
  try {
    const { dictType } = ctx.params
    const data = await SystemService.selectTypeToData(dictType)
    ctx.body = resDesign({ data })
  } catch (error) {
    console.log(error)
  }
})

module.exports = dictRouter
